  import React, { PureComponent } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { connect } from 'dva'
  import { formRules } from '@/utils/formRules'
import {
  Tabs,
  Button,
  Select,
  Table,
  Card,
  message,
  Icon,
  Modal,
  Form,
  Input,
  Upload,
  Popconfirm,
  Radio,
  Divider,
  Badge
} from 'antd'
import { LZFormItem } from '@/components/LZForm'
import commonApi from '@/services/common'
import { uploadUrl } from '@/config'
import { getToken } from '@/utils/localStorage'
import indexServices from './service'

const { TabPane } = Tabs
const { Option } = Select

const nameMap = {
  Banner: 'banner名称',
  icon: '图标名称',
  seal: '腰封名称',
}
  const platformDetail = {
    '1':'微信小程序',
    '2':'支付宝小程序',
    '3':'H5',
    '4':'APP',
  }
  const platformKey = {
    '微信小程序':'1',
    '支付宝小程序':'2',
    'H5':'3',
    'APP':'4',
  }
@connect()
@Form.create()
class IndexSetting extends PureComponent {
  state = {
    loading: false,
    onChannel: '1', // 默认
    newChannel: null,
    pageNumber: 1,
    pageSize: 10,
    total: 10,
    current: 1,
    selectedRowKeys: [],
    addVisible: false, // 控制添加modal的
    title: 'Banner添加', // 添加modal的标题
    fileList: [], // 图片
    bannerImage: '', // 上传成功后的url
    imgVisible: false,
    nameTitle: 'Banner名称',
    tabActiveKey: '1', // tab组件默认激活的
    editVisible: false,
    modalScore: 'add',
    address: 'Banner', // 编辑modal，目标位置的默认值
    name: null,
    url: null,
    sort: null,
    status: '1',
    img: null,
    id: null,
    size: 3,
    channelData: [],
    platform:'',
    getShopIndexBannerListByPage: [],
    sealTableData: [],
    cubeTableData: []
  }

  getColumns = () => {
    const type = this.state.tabActiveKey
    const map = {
      '1': ['Banner', this.deleteBanner,'商品'],
      '2': ['', () => {}],
      '3': ['腰封', this.deleteSeal,'分类'],
    }
    const text = map[type][0]
    const fn = map[type][1]
    const title = map[type][2]
    return [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        align: 'center'
      },
      {
        title: `${text}名称`,
        dataIndex: type === '4' ? 'name' : 'bannerName',
        align: 'center',
        key: type === '4' ? 'name' : 'bannerName'
      },
      {
        title: `${text}图片`,
        dataIndex: type === '4' ? 'imgUrl' : 'bannerImage',
        align: 'center',
        key: type === '4' ? 'imgUrl' : 'bannerImage',
        render: val => <img src={val} alt={val} className="table-cell-img" />
      },
      {
        title: `关联${title}`,
        dataIndex: title=== '分类' ?'categoryId' :'productId',
        align: 'center',
        key: title=== '分类' ?'categoryId' :'productId'
      },
      {
        title: '上架平台',
        dataIndex: 'platform',
        align: 'center',
        key: 'platform',
        render: val => {
          return <span>{platformDetail[val]}</span>
        }
      },
      {
        title: '上线时间',
        dataIndex: 'ctime',
        align: 'center',
        key: 'ctime'
      },
      {
        title: '状态',
        dataIndex: 'status',
        align: 'center',
        key: 'status',
        render: val => {
          const status = val ? 'success' : 'default'
          const badgeText = val ? '有效' : '失效'
          return <Badge status={status} text={badgeText} />
        }
      },
      {
        title: '排序',
        dataIndex: 'sort',
        align: 'center',
        key: 'sort'
      },
      {
        title: '操作',
        align: 'center',
        key: 'action',
        render: (val, record) => {
          return (
            <div className="table-action">
              <a onClick={() => this.edit(record)}>修改</a>
              <Divider type="vertical" />
              <Popconfirm title="你确定删除吗?" onConfirm={() => fn(record.id)}>
                <a>删除</a>
              </Popconfirm>
            </div>
          )
        }
      }
    ]
  }

  componentDidMount() {
    this.getBanner()
    this.getChannel()
  }

  // 获取上架渠道信息
  getChannel = () => {
    commonApi.selectPlateformChannel().then(res => {
      this.setState({
        channelData: res
      })
    })
  }

  // 获取banner的数据
  getBanner = () => {
    this.setState(
      {
        loading: true
      },
      () => {
        indexServices
          .getShopIndexBannerListByPage({
            pageNumber: this.state.pageNumber,
            pageSize: this.state.pageSize
          })
          .then(res => {
            message.success('获取banner信息成功')
            this.setState({
              total: res.total,
              getShopIndexBannerListByPage: res.records,
              current: res.current,
              loading: false
            })
          })
      }
    )
  }

  // 删除banner
  deleteBanner = id => {
    indexServices
      .deleteBanner({
        id
      })
      .then(res => {
        message.success('删除成功')
        this.getBanner()
      })
  }

  edit = record => {
    let address
    if (this.state.tabActiveKey === '1') {
      // 表示在banner位置，编辑的时候目标位置，需要显示的
      address = 'Banner'
    } else if (this.state.tabActiveKey === '2') {
      address = 'icon'
    } else if (this.state.tabActiveKey === '3') {
      address = 'seal'
    } else {
      address = 'cube'
    }
    const fileList = [
      {
        uid: 1,
        url: record.bannerImage ? record.bannerImage : record.imgUrl
      }
    ]
    this.setState(
      {
        addVisible: true,
        modalScore: 'edit',
        newChannel: this.state.onChannel,
        address,
        name: record.bannerName
          ? record.bannerName
          : record.iconName
          ? record.iconName
          : record.name,
        productId: record.productId,
        categoryId:record.categoryId,
        sort: record.sort,
        status: record.status,
        size: record.size,
        platform: record.platform,
        img: record.bannerImage ? record.bannerImage : record.imgUrl,
        fileList,
        // 提交用的
        bannerImage: record.bannerImage ? record.bannerImage : record.imgUrl,
        id: record.id
      },
      () => {}
    )
  }

  // 获取腰封
  getSeal = () => {
    this.setState(
      {
        loading: true
      },
      () => {
        // 腰封
        indexServices
          .getSealData({
            pageNumber: this.state.pageNumber,
            pageSize: this.state.pageSize
          })
          .then(res => {
            message.success('获取腰封信息成功')
            this.setState({
              sealTableData: res.records,
              total: res.total,
              current: res.current,
              loading: false
            })
          })
      }
    )
  }

  // 删除腰封
  deleteSeal = id => {
    indexServices.deleteSeal({ id }).then(res => {
      message.success('删除成功')
      this.getSeal()
    })
  }

  // 获取豆腐块
  getCube = () => {
    this.setState(
      {
        loading: true
      },
      () => {
        indexServices
          .getCubeData({
            pageNumber: this.state.pageNumber,
            pageSize: this.state.pageSize
          })
          .then(res => {
            message.success('获取豆腐块信息成功')
            this.setState({
              cubeTableData: res.records,
              total: res.total,
              current: res.current,
              loading: false
            })
          })
      }
    )
  }

  // 删除豆腐块
  deleteCube = id => {
    indexServices.deleteCube({ id }).then(res => {
      message.success('删除成功')
      this.getCube()
    })
  }

  // 切换tans的回调
  onTabChange = key => {
    if (key === '1') {
      // Banner
      this.setState({
        title: 'Banner添加',
        nameTitle: 'Banner名称',
        tabActiveKey: '1',
        address: 'Banner'
      })
    } else if (key === '2') {
      this.setState(
        {
          tabActiveKey: '2',
          title: 'Icon添加',
          nameTitle: '图标名称'
        },
        () => {
          this.getIcon()
        }
      )
    } else if (key === '3') {
      this.setState(
        {
          tabActiveKey: '3',
          title: '腰封添加',
          nameTitle: '腰封名称',
          address: 'seal'
        },
        () => {
          this.getSeal()
        }
      )
    } else {
      // 豆腐块
      this.setState(
        {
          title: '豆腐块添加',
          nameTitle: '豆腐块名称',
          tabActiveKey: '4',
          address: 'cube'
        },
        () => {
          this.getCube()
        }
      )
    }
  }

  handleFilter = () => {
    if (this.state.tabActiveKey === '1') {
      this.getBanner()
    } else if (this.state.tabActiveKey === '2') {
      this.getIcon()
    } else if (this.state.tabActiveKey === '3') {
      this.getSeal()
    } else if (this.state.tabActiveKey === '4') {
    }
  }

  // 分页，下一页
  onChange = pageNumber => {
    this.setState(
      {
        pageNumber
      },
      () => {
        this.handleFilter()
      }
    )
  }

  showTotal = () => {
    return `共有${this.state.total}条`
  }

  // 切换每页数量
  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize,
        pageNumber: 1
      },
      () => {
        this.handleFilter()
      }
    )
  }

  // 新增
  add = () => {
    this.setState({
      addVisible: true,
      newChannel: this.state.onChannel,
      modalScore: 'add',
      name: null,
      url: null,
      sort: null,
      status: '1',
      size: 3,
      img: null,
      channelName: [],
      platform:''
    })
  }

  renderCubeSize = () => {
    if (this.state.nameTitle !== '豆腐块名称') return null
    const { getFieldDecorator } = this.props.form
    const { size } = this.state
    return (
      <LZFormItem
        label="豆腐块的尺寸"
        field="size"
        requiredMessage="是否生效不能为空"
        getFieldDecorator={getFieldDecorator}
        initialValue={size || null}
      >
        <Radio.Group>
          <Radio value={1}>1(全幅)</Radio>
          <Radio value={2}>1/2</Radio>
          <Radio value={3}>1/3</Radio>
          <Radio value={4}>2/3</Radio>
        </Radio.Group>
      </LZFormItem>
    )
  }

  addressHandleChange = value => {
    this.setState({
      nameTitle: nameMap[value]
    })
  }

  // modal的确认，确认添加和确认更新的
  addOk = () => {
    this.props.form.validateFields((err, value) => {
      value.bannerImage = this.state.bannerImage
      const { size } = this.state
      if (!err) {
        const basePayload = {
          bannerName: value.bannerName,
          bannerImage: value.bannerImage,
          sort: JSON.parse(value.sort),
          productId: value.productId,
          status: (value.status == '1'? true :false) ,
          platform:this.state.modalScore === 'add' ? value.platform : platformKey[value.platform],
          categoryId:value.categoryId && JSON.parse(value.categoryId)
        }
        if (this.state.modalScore === 'add') {
          // 调用添加的
          if (value.address === 'Banner') {
            // 调用添加banner的接口
            indexServices.addBanner(basePayload).then(res => {
              message.success('添加banner成功')
              this.setState(
                {
                  addVisible: false,
                  fileList: [],
                  tabActiveKey: '1'
                },
                () => {
                  this.props.form.resetFields()
                  this.getBanner()
                }
              )
            })
          } else if (value.address === 'seal') {
            // 调用添加腰封的接口
            indexServices.addSeal(basePayload).then(res => {
              message.success('添加腰封成功')
              this.setState(
                {
                  addVisible: false,
                  fileList: [],
                  tabActiveKey: '3'
                },
                () => {
                  this.props.form.resetFields()
                  this.getSeal()
                }
              )
            })
          } else {
            // 调用添加豆腐块的接口
            basePayload.imgUrl = basePayload.bannerImage
            indexServices.addCube(basePayload).then(res => {
              message.success('添加豆腐块成功')
              this.setState(
                {
                  addVisible: false,
                  fileList: [],
                  tabActiveKey: '4'
                },
                () => {
                  this.props.form.resetFields()
                  this.getCube()
                }
              )
            })
          }
        } else {
          // 调用编辑的
          if (value.address === 'Banner') {
            // 调用更新banner的接口
            indexServices
              .updateBanner({
                id: this.state.id,
                platform:this.state.platform,
                ...basePayload
              })
              .then(res => {
                message.success('编辑成功')
                this.setState(
                  {
                    addVisible: false,
                    fileList: []
                  },
                  () => {
                    this.props.form.resetFields()
                    this.getBanner()
                  }
                )
              })
              .catch(err => {
                message.error(`编辑失败：${err.msg}`)
              })
          } else if (value.address === 'seal') {
            // 调用更新腰封的接口
            indexServices
              .updateSeal({
                id: this.state.id,
                ...basePayload
              })
              .then(res => {
                message.success('编辑成功')
                this.setState(
                  {
                    addVisible: false,
                    fileList: []
                  },
                  () => {
                    this.props.form.resetFields()
                    this.getSeal()
                  }
                )
              })
          } else {
            // 调用更新豆腐块的接口
            basePayload.imgUrl = basePayload.bannerImage
            indexServices
              .updateCube({
                id: this.state.id,
                name: value.bannerName,
                ...basePayload
              })
              .then(res => {
                message.success('编辑成功')
                this.setState(
                  {
                    addVisible: false,
                    fileList: []
                  },
                  () => {
                    this.props.form.resetFields()
                    this.getCube()
                  }
                )
              })
          }
        }
      }
    })
  }

  // 上传的回调
  handleUploadChange = ({ file, fileList, event }) => {
    const filelist = [...fileList] || []
    if (file.status == 'done') {
      filelist.map(item => {
        this.setState({
          bannerImage: item.response.data
        })
      })
    }
    this.setState({
      fileList
    })
  }

  // 上传后预览的回调
  handlePreview = () => {
    this.setState({
      imgVisible: true
    })
  }

  onDownload = () => {
    return window.open(this.state.bannerImage)
  }

  // 上传后删除的回调
  onRemove = () => {
    this.setState(
      {
        fileList: [],
        bannerImage: ''
      },
      () => {}
    )
  }
  render() {
    const {
      loading,
      total,
      current,
      selectedRowKeys,
      addVisible,
      fileList,
      imgVisible,
      bannerImage,
      nameTitle,
      tabActiveKey,
      modalScore,
      address,
      name,
      url,
      sort,
      status,
      img,
      channelData,
      channelName,
      productId,
      getShopIndexBannerListByPage,
      cubeTableData,
      sealTableData,
      platform,
      categoryId,
    } = this.state

    const pagination = {
      current,
      total,
      onChange: this.onChange,
      showTotal: this.showTotal,
      showQuickJumper: true,
      pageSizeOptions: ['5', '10', '20'],
      showSizeChanger: true,
      onShowSizeChange: this.onShowSizeChange
    }

    const { getFieldDecorator } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    )

    return (
      <PageHeaderWrapper title={false} className="index-configure">
        <Card bordered={false}>
          <Tabs
            activeKey={tabActiveKey}
            animated={false}
            onChange={this.onTabChange}
            tabBarExtraContent={
              <div>
                <Button type="primary" onClick={this.add}>
                  新增
                </Button>
              </div>
            }
          >
            <TabPane tab="Banner" key="1">
              <Table
                columns={this.getColumns()}
                loading={loading}
                tableLayout="fixed"
                dataSource={getShopIndexBannerListByPage}
                rowKey={record => record.id}
                pagination={pagination}
              />
            </TabPane>
            <TabPane tab="腰封" key="3">
              <Table
                columns={this.getColumns()}
                loading={loading}
                tableLayout="fixed"
                dataSource={sealTableData}
                rowKey={record => record.id}
                pagination={pagination}
              />
            </TabPane>
          </Tabs>
        </Card>
        <Modal
          title={modalScore === 'add' ? '新增' : '修改'}
          visible={addVisible}
          onCancel={() => {
            this.setState({
              addVisible: false,
              onChannel: this.state.newChannel,
              fileList: []
            })
            this.props.form.resetFields()
          }}
          onOk={this.addOk}
        >
          <Form {...formItemLayout}>
            <Form.Item label="目标位置">
              {getFieldDecorator('address', {
                rules: [
                  {
                    required: true,
                    message: '目标位置不能为空'
                  }
                ],
                initialValue: address || null
              })(
                <Select onChange={this.addressHandleChange} disabled>
                  <Option value="Banner">Banner</Option>
                  {/* <Option value="icon">图标</Option> */}
                  <Option value="seal">腰封</Option>
                  <Option value="cube">豆腐块</Option>
                </Select>
              )}
            </Form.Item>
            {this.renderCubeSize()}
            <Form.Item label={nameTitle}>
              {getFieldDecorator('bannerName', {
                rules: [
                  {
                    required: true,
                    message: `${nameTitle}不能为空`
                  }
                ],
                initialValue: name || null
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label= {this.state.tabActiveKey === '1' ? '关联商品' :'关联分类'}>
              {getFieldDecorator(this.state.tabActiveKey=== '1' ? 'productId' :'categoryId', {
                rules: [
                  {
                    required: true,
                    message:this.state.tabActiveKey === '1' ? '关联商品不能为空':'关联分类只能为正整数',
                    pattern:this.state.tabActiveKey !=='1' ? /^[1-9]\d*$/ :''
                  }
                ],
                initialValue:this.state.tabActiveKey === '1' ? productId : categoryId|| null
              })(<Input placeholder="请输入"  />)}
            </Form.Item>
            <Form.Item label="排序规则">
              {getFieldDecorator('sort', {
                rules: [
                  {
                    required: true,
                    message: '排序规则不能为空'
                  }
                ],
                initialValue: sort || null
              })(<Input placeholder="请输入" />)}
            </Form.Item>
            <Form.Item label="是否生效1">
              {getFieldDecorator('status', {
                initialValue: status ? '1' :'0'
              })(
                <Radio.Group>
                  <Radio value ='1'>生效</Radio>
                  <Radio value='0'>不生效</Radio>
                </Radio.Group>
              )}
            </Form.Item>
            <Form.Item label="上传图片">
              {getFieldDecorator('bannerImage', {
                rules: [
                  {
                    validator: (rule, value, callback) => {
                      const { form } = this.props
                      if (!this.state.bannerImage) {
                        callback('图片不能为空')
                      }
                      callback()
                    }
                  }
                ],
                initialValue: img || null
              })(
                <Upload
                  accept="image/*"
                  action={uploadUrl}
                  headers={{
                    token: getToken()
                  }}
                  listType="picture-card"
                  fileList={fileList}
                  onPreview={this.handlePreview} // 预览
                  onRemove={this.onRemove} // 删除
                  onDownload={this.onDownload}
                  onChange={this.handleUploadChange}
                >
                  {fileList.length >= 1 ? null : uploadButton}
                </Upload>
              )}
            </Form.Item>
            <Form.Item label="上架平台">
              {getFieldDecorator('platform', {
                rules: [
                  {
                    required: true,
                    message: '上架平台不能为空'
                  }
                ],
                initialValue: platformDetail[platform] || ''
              })(
                <Select placeholder='请选择上架平台' style={{ width: 250 }}>
                  <Option value="1">微信小程序</Option>
                  <Option value="2">支付宝小程序</Option>
                  <Option value="3">H5</Option>
                  <Option value="4">App</Option>
                </Select>
              )}
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          visible={imgVisible}
          footer={null}
          onCancel={() => this.setState({ imgVisible: false })}
          width={600}
        >
          <img
            src={bannerImage || null}
            alt=""
            style={{ width: '100%', paddingTop: 15 }}
          />
        </Modal>
      </PageHeaderWrapper>
    )
  }
}

export default IndexSetting
